package cn.i7baozh.starter.common.controller;

import cn.i7baozh.starter.common.response.VoidResponseResult;
import cn.i7baozh.starter.common.response.WebResponseResult;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.http.entity.ContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpStatus;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodReturnValueHandler;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletResponse;
import java.nio.charset.StandardCharsets;

/**
 * 使用@RestClientApi注解的controller方法，以封装好的方式将其返回json
 * @author: baoqi.zhang
 * @date: 2020/6/1 20:17
 */
public class GatewayRestClientApiHandler extends AbstractHandler implements HandlerMethodReturnValueHandler {

    @Autowired
    private ObjectMapper objectMapper;

    @Override
    protected HandlerMethodReturnValueHandler getHandler() {
        return this;
    }

    @Override
    public boolean supportsReturnType(MethodParameter methodParameter) {
        return methodParameter.getMethodAnnotation(GatewayRestClientApi.class) != null;
    }

    @Override
    public void handleReturnValue(Object returnValue, MethodParameter returnType, ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest) throws Exception {
        //设置为true 表示不在去找view视图了
        modelAndViewContainer.setRequestHandled(true);

        HttpServletResponse httpServletResponse = nativeWebRequest.getNativeResponse(HttpServletResponse.class);;
        WebResponseResult webResponseResult = new WebResponseResult();
        webResponseResult.setCode(HttpStatus.OK.value());
        webResponseResult.setMessage(HttpStatus.OK.getReasonPhrase());
        if (returnValue == null) {
            String name = returnType.getParameterType().getName();
            if (void.class.getName().equals(name) || Void.class.getName().equals(name)) {
                //给个默认值即可
                webResponseResult.setData(new VoidResponseResult(1));
            }
        } else if ( returnValue instanceof WebResponseResult) {
            webResponseResult = (WebResponseResult) returnValue;
        } else {
            webResponseResult.setData(returnValue);
        }
        String text = getOutputText(webResponseResult);
        byte[] bytes = text.getBytes(StandardCharsets.UTF_8);
        assert httpServletResponse != null;
//        httpServletResponse.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
        httpServletResponse.setContentType(ContentType.APPLICATION_JSON.toString());
        FileCopyUtils.copy(bytes, httpServletResponse.getOutputStream());
    }

    /**
     * 获取内容
     *
     * @param webResponseResult
     * @return
     */
    protected String getOutputText(WebResponseResult webResponseResult) {
        try {
            return objectMapper.writeValueAsString(webResponseResult);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return null;
    }
}
